package com.mazegame.frontend;

import com.mazegame.backend.StorySceneManager;
import com.mazegame.backend.TextAnimation;
import com.mazegame.backend.UserDAO;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.media.AudioClip;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;

import javax.swing.*;
import java.awt.*;
import java.net.URI;
import java.net.URISyntaxException;

import javafx.scene.control.Label;

public class FirstStoryPanel extends JPanel implements GamePanel {
    private CardLayout cardLayout;
    private JPanel cardPanel;
    private JLayeredPane layeredPane;
    private static final int WIDTH = 1500;
    private static final int HEIGHT = 900;
    private JFXPanel jfxPanel;
    // 故事场景管理器
    private static StorySceneManager sceneManager;
    // 获取当前登录的用户名和ID
    int userId;
    // 目标章节
    int targetChapter = 1;
    static double sound = 0.5;


    //第一个场景要用到的
    private TextAnimation animation1;
    private TextAnimation animation2;
    private Text text1;
    private Text text2;
    private static final String CONTENT1 = "\u3000\u3000你叫莉娜，是一名考古天文学家，你追踪着祖辈留下的星图线索来到沙漠中，这里的文明已经消失，只留下残缺的神庙。你发现当星轨位移，神庙就会发生改变，而神庙周围有一群星灵守卫警惕地巡视着。想要探索神庙的秘密需要顺利进入神庙和躲避守卫。";
    private static final String CONTENT2 = "\u3000\u3000一阵风暴来袭，你躲在附近的岩石洞中，等风暴停止后，你发现风暴中心的巨石阵其实就是神庙入口。祖父的星盘突然发出蓝光，石阵中间出现一道由沙尘聚成的入口，莉娜通过入口进入神庙，发现眼前有一个沙子聚成的迷宫，看来神庙内部就是一座会随着星象变换的活体迷宫，想要一探究竟只有通过迷宫了……";
    private static AudioClip typingSound; // 音效对象
    private boolean isFirstClick = true; // 标记是否是第一次点击

    // 第二个场景要用到的
    private TextAnimation animation3;
    private Text text3;
    private static final String CONTENT3 = "\u3000\u3000我是星灵守卫，我不允许任何人靠近天枢之眼。如果你碰到了我，我会攻击你，但是我很惧怕星辰之力。";
    private boolean isFirstClick2 = true; // 标记是否是第一次点击

    // 第三个场景要用到的
    private TextAnimation animation4;
    private Text text4;
    private static final String CONTENT4 = "\u3000\u3000既然如此，我是不是可以躲避或者借助星辰之力击退怪物。";
    private boolean isFirstClick3 = true;

    // 第四个场景要用到的
    private static TextAnimation animation5;
    private static Text text5;
    private static final String CONTENT5 = "\u3000\u3000通过沙子迷宫后，你发现身后的迷宫消失了，而你面前矗立着一座有文字雕刻的巨石，仔细阅读巨石上的文字，发现上面记载着一千年前人们在这里幸福的生活，但巨石只记载了一部分，看来巨石上记载的历史正文就是探索天枢之眼的关键。你做好笔记稍作休息后继续进行探索。";
    private boolean isFirstClick4 = true;

    public FirstStoryPanel(CardLayout cardLayout, JPanel cardPanel) {
        this.cardLayout = cardLayout;
        this.cardPanel = cardPanel;
        initializeUI();
    }
    private void initializeUI() {
        // 使用 JLayeredPane 管理不同层级的组件
        layeredPane = new JLayeredPane();
        setLayout(new BorderLayout());
        add(layeredPane, BorderLayout.CENTER);
        // 创建 JavaFX 内容面板
        jfxPanel = new JFXPanel();
        jfxPanel.setOpaque(false);
        jfxPanel.setBounds(0, 0, WIDTH, HEIGHT);
        layeredPane.add(jfxPanel, JLayeredPane.MODAL_LAYER);
        Platform.runLater(() -> {
            // 创建场景管理器
            sceneManager = new StorySceneManager();
            // 创建主容器
            BorderPane root = createContentPane();
            root.setStyle("-fx-background-color: rgba(0, 0, 0, 0);");
            // 将场景管理器的根节点添加到主容器中心
            root.setCenter(sceneManager.getRoot());
            // 创建透明场景
            Scene scene = new Scene(root, WIDTH, HEIGHT, Color.TRANSPARENT);
            jfxPanel.setScene(scene);
            // 初始化并显示第一个场景
            initScenes();
            sceneManager.showScene("scene0");
        });
    }
    private BorderPane createContentPane() {
        return new BorderPane();
    }
    // 初始化故事中的所有场景
    private void initScenes() {
        StackPane scene5 = createScene5();
        sceneManager.addScene("scene5", addBackground(scene5, "/img/黑色背景.png"));
        StackPane scene0 = createScene0();
        sceneManager.addScene("scene0", addBackground(scene0, "/img/黑色背景.png"));
        StackPane scene1 = createScene1();
        sceneManager.addScene("scene1", addBackground(scene1, "/img/石柱.png"));
        StackPane scene2 = createScene2();
        sceneManager.addScene("scene2", addBackground(scene2, "/img/怪兽场景.jpg"));
        StackPane scene3 = createScene3();
        sceneManager.addScene("scene3", addBackground(scene3, "/img/主角场景.png"));
        StackPane scene4 = createScene4();
        sceneManager.addScene("scene4", addBackground(scene4, "/img/石头2.png"));
    }
    // 添加背景图的方法
    private Pane addBackground(Pane content, String imagePath) {
        ImageView background = new ImageView(new Image(getClass().getResourceAsStream(imagePath)));
        background.setFitWidth(WIDTH);
        background.setFitHeight(HEIGHT);
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(background, content);
        return stackPane;
    }
    private StackPane createScene0() {
        StackPane root = new StackPane();
        Text content = new Text("\u3000\u3000第一章");
        content.setWrappingWidth(900);
        content.setFont(new Font("微软雅黑", 48));
        content.setFill(Color.WHITE);
        content.setVisible(true);
        VBox textbox = new VBox(40);//每个文本间隔20
        textbox.getChildren().add(content);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new Insets(0));//页边距20
        textbox.setPrefSize(900, 600);
        textbox.setMaxSize(900, 600);
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 32));
        tip.setTextFill(Color.WHITE);
        root.setMargin(textbox,new Insets(0,0,200, 520));
        root.setMargin(tip,new Insets(500,0,0,0));
        root.getChildren().addAll(textbox, tip);
        // 添加点击事件：点击任意位置切换到下一个场景
        root.setOnMouseClicked(event -> {
            startFirstStory();
            sceneManager.showScene("scene1"); // 点击后跳转到 scene1
        });
        return root;
    }
    private StackPane createScene1() {
        // 构建文本1
        text1 = new Text("");
        text1.setWrappingWidth(820);
        text1.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text1.setFill(Color.BLACK);
        // 构建文本2
        text2 = new Text("");
        text2.setWrappingWidth(820);
        text2.setFont(new Font("微软雅黑", 32));
        text2.setFill(Color.BLACK);
        text2.setVisible(false); // 最开始不展示text2
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text1, text2);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new Insets(20));//页边距20
        textbox.setPrefSize(900, 600);
        textbox.setMaxSize(900, 600);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(Color.WHITE);

        StackPane.setMargin(textbox, new Insets(0,0 ,100,0));
        StackPane.setMargin(tip, new Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick) {
                stopAnimationAndSound();
                isFirstClick = false;  // 更新状态为已点击一次
            } else {
                // 第二次点击：跳转到下一个场景
                sceneManager.showScene("scene2");
                startFirstStory2();
            }
        });
        return stackPane;
    }
    private StackPane createScene2() {
        // 构建文本1
        text3 = new Text("");
        text3.setWrappingWidth(600);
        text3.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text3.setFill(Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text3);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new Insets(20));//页边距20
        textbox.setPrefSize(640, 200);
        textbox.setMaxSize(640, 200);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(Color.WHITE);
        StackPane.setMargin(textbox, new Insets(200,270 ,0,0));
        StackPane.setMargin(tip, new Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick2) {
                stopAnimationAndSound2();
                isFirstClick2 = false;  // 更新状态为已点击一次
            } else {
                // 第二次点击：跳转到下一个场景
                sceneManager.showScene("scene3");
                startFirstStory3();
            }
        });
        return stackPane;
    }
    private StackPane createScene3() {
        // 构建文本1
        text4 = new Text("");
        text4.setWrappingWidth(600);
        text4.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text4.setFill(Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text4);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new Insets(20));//页边距20
        textbox.setPrefSize(640, 200);
        textbox.setMaxSize(640, 200);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(Color.WHITE);

        StackPane.setMargin(textbox, new Insets(270,0 ,0,200));
        StackPane.setMargin(tip, new Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick3) {
                stopAnimationAndSound3();
                isFirstClick3 = false;  // 更新状态为已点击一次
            } else {
                // 进迷宫
                MazeGeneratePanel.isFirst = true;
                BufferPanel.isFirst = true;
                cardLayout.show(cardPanel, "MAZEGENERATEPANEL");
            }
        });
        return stackPane;
    }
    private StackPane createScene4() {
        // 构建文本1
        text5 = new Text("");
        text5.setWrappingWidth(820);
        text5.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text5.setFill(Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text5);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new Insets(20));//页边距20
        textbox.setPrefSize(800, 350);
        textbox.setMaxSize(800, 350);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(Color.WHITE);

        StackPane.setMargin(textbox, new Insets(0,0 ,100,0));
        StackPane.setMargin(tip, new Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick4) {
                stopAnimationAndSound4();
                isFirstClick4 = false;  // 更新状态为已点击一次
            } else {
                // 第二次点击：跳转到下一个场景
                sceneManager.showScene("scene5");
                //cardLayout.show(cardPanel, "CHARACTERPANEL");
            }
        });
        return stackPane;
    }
    private StackPane createScene5() {
        StackPane root = new StackPane();
        Text content = new Text("\u3000\u3000第一章结束");
        content.setWrappingWidth(900);
        content.setFont(new Font("微软雅黑", 48));
        content.setFill(Color.WHITE);
        content.setVisible(true);
        VBox textbox = new VBox(40);//每个文本间隔20
        textbox.getChildren().add(content);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new Insets(0));//页边距20
        textbox.setPrefSize(900, 600);
        textbox.setMaxSize(900, 600);
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 32));
        tip.setTextFill(Color.WHITE);
        root.setMargin(textbox,new Insets(0,0,200, 430));
        root.setMargin(tip,new Insets(500,0,0,0));
        root.getChildren().addAll(textbox, tip);
        root.setOnMouseClicked(event -> {
            update();
        });
        return root;
    }
    private void update() {
        targetChapter = 2; // 解锁第二章节
        if(targetChapter>ChapterPanel.currentChapter){
            userId = Integer.parseInt(LoginPanel.currentUserId);
            // 保存游戏进度
            if (UserDAO.updateChapter(userId, targetChapter)) {
                System.out.println("游戏进度保存成功！");
            } else {
                System.out.println("游戏进度保存失败！");
            }
            ChapterPanel.update();
        }
        // 切换回章节界面
        cardLayout.show(cardPanel, "CHAPTERPANEL");
        // 重置
        text1.setText("");
        text2.setText("");
        text3.setText("");
        text4.setText("");
        text5.setText("");
        isFirstClick = true;
        isFirstClick2 = true;
        isFirstClick3 = true;
        isFirstClick4 = true;
        sceneManager.showScene("scene0");
    }
    public void stopAnimationAndSound(){
        // 停止动画和音效，显示全文
        if (animation1 != null) {
            animation1.stop(); // 现在可以调用 stop
        }
        if (animation2 != null) {
            animation2.stop();
        }
        typingSound.stop();
        text1.setText(CONTENT1);
        text2.setText(CONTENT2);
        text2.setVisible(true);
        isFirstClick = false;
    }
    public void stopAnimationAndSound2(){
        // 停止动画和音效，显示全文
        if (animation3 != null) {
            animation3.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text3.setText(CONTENT3);
        isFirstClick = false;
    }
    public void stopAnimationAndSound3(){
        // 停止动画和音效，显示全文
        if (animation4 != null) {
            animation4.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text4.setText(CONTENT4);
        isFirstClick = false;
    }
    public void stopAnimationAndSound4(){
        // 停止动画和音效，显示全文
        if (animation5 != null) {
            animation5.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text5.setText(CONTENT5);
        isFirstClick4 = false;
    }
    public void startFirstStory() {
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = getClass().getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(sound);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放

        // 启动第一个文本动画
        animation1 = new TextAnimation(
                text1,
                CONTENT1,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation1.start();

        // 第一个文本完成后启动第二个
        animation1.setOnFinished(() -> {
            text2.setVisible(true);
            animation2 = new TextAnimation(
                    text2,
                    CONTENT2,
                    TextAnimation.DEFAULT_CHARACTER_DELAY,
                    TextAnimation.DEFAULT_TEXT_DELAY,
                    typingSound
            );
            animation2.start();
        });
    }
    public void startFirstStory2() {
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = getClass().getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(sound);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动第一个文本动画
        animation3 = new TextAnimation(
                text3,
                CONTENT3,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation3.start();
    }
    public void startFirstStory3() {
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = getClass().getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(sound);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动第一个文本动画
        animation4 = new TextAnimation(
                text4,
                CONTENT4,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation4.start();
    }
    public static void startFirstStory4() {
        sceneManager.showScene("scene4");
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = FirstStoryPanel.class.getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(sound);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动本动画
        animation5 = new TextAnimation(
                text5,
                CONTENT5,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation5.start();
    }

    @Override
    public void showPanel() {
        cardLayout.show(cardPanel, "FIRSTSTORYPANEL");
    }

    @Override
    public void cleanup() {
        // 清理资源
    }



}